package org.esir.lib_java.thread

import java.util.concurrent.Executors
import java.util.concurrent.LinkedBlockingDeque
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit

/**
 * 线程池
 */
object ThreadPool {
    /*
   池管理维护一个可执行线程的线程池作为执行调用者给预的任务
   TODO 可配置不同参数线程池
    */
    /**非核心线程可存活时间*/
    private var keepAliveTime: Long = 60
    /**CPU核数：可为设置核心线程数提供数据参照*/
    private val cpuNum = Runtime.getRuntime().availableProcessors()
    private var corePoolSize: Int = cpuNum * 2
    private var maximumPoolSize: Int = cpuNum * 2 + 1
    var executor: ThreadPoolExecutor? = null

    /**
     * 在线程里执行一个代码段
     *
     * @param runnable {@linkplain Runnable}
     */
    fun execute(runnable: Runnable?) {
        if (executor == null) {
            executor = createDefault()
        }
        executor?.execute(runnable)
    }

    /**
     * 从线程队列中移除对象
     *
     * @param runnable {@linkplain Runnable}
     */
    fun cancel(runnable: Runnable?) {
        if (executor != null) {
            executor?.queue?.remove(runnable)
        }
    }

    /**
     * 创建一个默认的线程执行者
     */
    fun createDefault(): ThreadPoolExecutor {
        return ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                TimeUnit.MILLISECONDS,
                LinkedBlockingDeque(1024),
                Executors.defaultThreadFactory(),// 线程工厂(TODO 建议替换其他线程工场，在创建线程标记名称，为追究问题提供指引)
                object : ThreadPoolExecutor.AbortPolicy() {
                }
        )
    }


}